package com.javawork.juc.three;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition中的线程等待和唤醒方法，需要先获取锁一定要先await后signal，不要反
 * @author zhangxiaolu
 * @since 2023-02-09 22:30
 */
public class LockConditionAwaitAndSignal {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "---come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "------被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "------发出唤醒");
            }finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}
